package com.nuc.seckill.controller;

import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.nuc.seckill.base.BaseResponse;
import com.nuc.seckill.base.Constant;
import com.nuc.seckill.entity.ImageCode;
import com.nuc.seckill.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 验证码
 *
 * @author 石一歌
 * @date 2022-08-14 23:08
 */
@Controller
@RequestMapping(value = "/seckill")
@Slf4j
public class VerifyCodeController {
    @Resource
    private DefaultKaptcha defaultKaptcha;
    @Resource
    private RedisUtil redisUtil;

    @RequestMapping("/code")
    @ResponseBody
    public BaseResponse<ImageCode> getNumCode() throws IOException {
        String imageId = IdUtil.objectId();
        // 获得二进制输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 通过DefaultKaptcha获得随机验证码
        String code = defaultKaptcha.createText();
        BufferedImage image = defaultKaptcha.createImage(code);
        // 将图片写入到流中
        ImageIO.write(image, "jpg", baos);
        ImageCode vo = new ImageCode();
        vo.setImageId(imageId);
        vo.setImageStr(Base64.encodeBase64String(baos.toByteArray()));
        redisUtil.set(String.format(Constant.RedisKey.SECKILL_IMAGE_CODE, imageId), code, 60);
        return BaseResponse.ok(vo);
    }

    @RequestMapping("/page")
    public String index() {
        return "code";
    }
}
